//
//  WBRefreshControl.swift
//  WeiBo
//
//  Created by 小小罗 on 15/11/15.
//  Copyright © 2015年 RealMadrid. All rights reserved.
//

import UIKit


// 下拉刷新动画偏移量
private let WBRefreshControlOffset: CGFloat = -60


//微博刷新控件  -负责刷新业务逻辑
class WBRefreshControl: UIRefreshControl {

    override func endRefreshing() {
        super.endRefreshing()
        
        refreshView.stopAnimation()
        
        
        
    }
    
    override func beginRefreshing() {
        super.beginRefreshing()
        
        refreshView.startAnimation()
    }

    
    
    //MARK: - 监听方法

    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        print(frame)
        
        if frame.origin.y > 0 { return }
        //判断是否正在刷新
        if refreshing {
            refreshView.startAnimation()
            return
        }
        
        if frame.origin.y < WBRefreshControlOffset && !refreshView.rotateFlag {
            print("翻过来")
            refreshView.rotateFlag = true
        } else if frame.origin.y > WBRefreshControlOffset && refreshView.rotateFlag {
            print("转过去")
            refreshView.rotateFlag = false
        }
    }
    
    
    //构造函数
    override init() {
        super.init()
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setUpUI()
    }
    //设置界面
    private func setUpUI() {
    
        // 设置 tintColor
        tintColor = UIColor.clearColor()

        
        //1.添加控件
        addSubview(refreshView)
        
        //2.自动布局
        refreshView.snp_makeConstraints { (make) -> Void in
            
            make.centerX.equalTo(self.snp_centerX)
            make.centerY.equalTo(self.snp_centerY)
            
            make.size.equalTo(refreshView.bounds.size)
            
        }
        
        //3.KVO监听  
        //添加到主队列  等待主线程上的其他任务执行完毕后再执行
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
                self.addObserver(self, forKeyPath: "frame", options: [], context: nil)
            
            
        }
    
    }
    
    //移除监听
    deinit {
        self.removeObserver(self, forKeyPath: "frame")
    }
    
    //懒加载控件
    private lazy var refreshView : WBRefreshView = WBRefreshView.refreshView()
    

}

//微博刷新视图  负责刷新动画显示
class WBRefreshView : UIView {
    
    // 旋转标记
    private var rotateFlag = false {
        didSet {
            rotateTipIcon()
        }
    }
    
    // 旋转提示图标
    @IBOutlet weak var tipIconView: UIImageView!
    //提示视图
    @IBOutlet weak var tipView: UIView!
    //加载图标
    @IBOutlet weak var loadingIconView: UIImageView!
    
    
    //加载xib
    class func refreshView() -> WBRefreshView {
        
        let nib = UINib(nibName: "WBRefreshView", bundle: nil)
        
        return nib.instantiateWithOwner(nil, options: nil).last as! WBRefreshView
        
    }
    
    // 旋转提示图标
    private func rotateTipIcon() {
        
        var angle = CGFloat(M_PI)
        angle += rotateFlag ? -0.00000001 : 0.00000001
        
        UIView.animateWithDuration(0.5) {
            self.tipIconView.transform = CGAffineTransformRotate(self.tipIconView.transform, angle)
        }
    }

    // 开始动画
    private func startAnimation() {
        loadingIconView.hidden = false
        let keyPath = "transform.rotation"
        if loadingIconView.layer.animationForKey(keyPath) != nil {
            return
        }
        
        tipView.hidden = true
        
        let anim = CABasicAnimation(keyPath: keyPath)
        
        anim.toValue = 2 * M_PI
        anim.repeatCount = MAXFLOAT
        anim.duration = 0.5
        anim.removedOnCompletion = false
        
        loadingIconView.layer.addAnimation(anim, forKey: keyPath)
    }
    
    // 停止动画
    private func stopAnimation() {
        tipView.hidden = false
        loadingIconView.hidden = true
        loadingIconView.layer.removeAllAnimations()
    }




}





